import React, { useState, useEffect } from 'react';
import { Select, Input, Button, message, Modal, Form } from 'antd';
import ResMethod from '../utils/ResMethod';
import CourseTables from '../tables/CourseTables';

const CourseList: React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  async function getCourseData() {
    const data = await ResMethod('/course', 'GET');
    if (data){
      if (data === 401){
      messageApi.info({
        type: 'error',
        content: '登录过期，请重新登录'
      });
      setTimeout(()=> {
        window.location.href = '/login';
      }, 400)
    } else {
      setCourseData(data);
    }
    }


  }

  const Suinfo = () => {
    messageApi.info({
      type: 'success',
      content: '操作成功'
    });
  };

  const Errinfo = () => {
    messageApi.info({
      type: 'error',
      content: '操作失败'
    });
  };

  const [name, setName] = useState('');
  const [time, setTime] = useState(1);
  const [week_day, setWeek] = useState(1);
  const [teacher, setTeacher] = useState('');
  const [place, setPlace] = useState('');

  const onTimeSelected = (value: number) => {
    setTime(value);
  };

  const onWeekSelected = (value: number) => {
    setWeek(value);
  };

  const filterCourseData = async () => {
    const params: object = {
      week_day,
      time,
      name,
      teacher,
      place
    };

    const data = await ResMethod('/course', 'GET', params);
    if (data !== 'err') {
      Suinfo();
      return setCourseData(data);
    } else {
      Errinfo();
    }
  };

  const handleAdd = async () => {
    try {
      const values = await form.validateFields();
      const data = await ResMethod('/course', 'POST', values);
      if (data) {
        Suinfo();
        setIsModalVisible(false);
        getCourseData();
        form.resetFields();
      } else {
        Errinfo();
      }
    } catch (error) {
      console.error('验证失败:', error);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const handleDelete = async (id: number) => {
    const data = await ResMethod(`/course/${id}`, 'DELETE');
    if (data) {
      Suinfo();
      getCourseData();
    } else {
      Errinfo();
    }
  };

  const handleUpdate = async (values: any) => {
    const data = await ResMethod('/course', 'PUT', values);
    if (data) {
      Suinfo();
      getCourseData();
    } else {
      Errinfo();
    }
  };

  const [courseData, setCourseData] = useState([
  ]);

  useEffect(() => {
    getCourseData();
  }, []);

  return (
    <div className="h-full flex flex-col jusetify-center p-12 w-full">
      {contextHolder}
      <div className="flex flex-row items-center w-full">
        <span className="mr-3 font-normal text-md">星期</span>
        <Select
          style={{ width: 80 }}
          defaultValue={1}
          onChange={onWeekSelected}
          options={[
            { value: '1', label: '1 - 周一' },
            { value: '2', label: '2 - 周二' },
            { value: '3', label: '3 - 周三' },
            { value: '4', label: '4 - 周四' },
            { value: '5', label: '5 - 周五' }
          ]}
        />
        <span className="mx-3 font-normal text-md">节次</span>
        <Select
          style={{ width: 120 }}
          defaultValue={1}
          onChange={onTimeSelected}
          options={[
            { value: '1', label: '1 - 一二节' },
            { value: '2', label: '2 - 三四节' },
            { value: '3', label: '3 - 五六节' },
            { value: '4', label: '4 - 七八节' },
            { value: '5', label: '5 - 九十节' }
          ]}
        />
        <span className="mx-3 font-normal text-md">课程</span>
        <Input
          placeholder="请输入课程名称"
          className="max-w-45"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <span className="mx-3 font-normal text-md">教师</span>
        <Input
          placeholder="请输入教师姓名"
          className="max-w-45"
          value={teacher}
          onChange={(e) => setTeacher(e.target.value)}
        />
        <span className="mx-3 font-normal text-md">位置</span>
        <Input
          placeholder="请输入上课地点"
          className="max-w-45"
          value={place}
          onChange={(e) => setPlace(e.target.value)}
        />
        <Button type="primary" className="ml-3" onClick={filterCourseData}>
          查询
        </Button>
        <Button className="ml-3" onClick={() => setIsModalVisible(true)}>
          新增
        </Button>
      </div>
      <div className="mt-5">
        <CourseTables
          dataSource={courseData}
          onDelete={handleDelete}
          onUpdate={handleUpdate}
        />
      </div>

      <Modal
        title="新增课程"
        open={isModalVisible}
        onOk={handleAdd}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">


          <Form.Item
            name="week_day"
            label="星期"
            rules={[{ required: true, message: '请选择星期' }]}
          >
            <Select>
              <Select.Option value={1}>周一</Select.Option>
              <Select.Option value={2}>周二</Select.Option>
              <Select.Option value={3}>周三</Select.Option>
              <Select.Option value={4}>周四</Select.Option>
              <Select.Option value={5}>周五</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="time"
            label="节次"
            rules={[{ required: true, message: '请选择节次' }]}
          >
            <Select>
              <Select.Option value={1}>1 - 一二节</Select.Option>
              <Select.Option value={2}>2 - 三四节</Select.Option>
              <Select.Option value={3}>3 - 五六节</Select.Option>
              <Select.Option value={4}>4 - 七八节</Select.Option>
              <Select.Option value={5}>5 - 九十节</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="课程名称"
            rules={[{ required: true, message: '请输入课程名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="teacher"
            label="授课教师"
            rules={[{ required: true, message: '请输入授课教师' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="place"
            label="上课地点"
            rules={[{ required: true, message: '请输入上课地点' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CourseList;